import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { AppMode, AppSettings, ShortcutConfig, WindowInfo } from '../types';

interface AppState {
  // 应用模式
  currentMode: AppMode;
  setCurrentMode: (mode: AppMode) => void;
  
  // 窗口状态
  opacity: number;
  setOpacity: (opacity: number) => void;
  
  alwaysOnTop: boolean;
  setAlwaysOnTop: (alwaysOnTop: boolean) => void;
  
  isVisible: boolean;
  setIsVisible: (isVisible: boolean) => void;
  
  windowInfo: WindowInfo | null;
  setWindowInfo: (windowInfo: WindowInfo) => void;
  
  // 透明度预设
  opacityPresets: number[];
  setOpacityPresets: (presets: number[]) => void;
  
  // 快捷键配置
  shortcuts: ShortcutConfig;
  setShortcuts: (shortcuts: ShortcutConfig) => void;
  
  // 应用设置
  settings: AppSettings;
  setSettings: (settings: AppSettings) => void;
  updateSetting: <K extends keyof AppSettings>(key: K, value: AppSettings[K]) => void;
  
  // 微信读书相关
  wechatReadUrl: string;
  setWechatReadUrl: (url: string) => void;
  
  isLoggedIn: boolean;
  setIsLoggedIn: (isLoggedIn: boolean) => void;
  
  // 伪装模式相关
  disguiseSettings: {
    theme: 'dark' | 'light';
    projectName: string;
    activeFile: string;
    terminalOutput: string[];
  };
  setDisguiseSettings: (settings: Partial<AppState['disguiseSettings']>) => void;
  
  // 操作方法
  toggleMode: () => void;
  toggleVisibility: () => void;
  increaseOpacity: () => void;
  decreaseOpacity: () => void;
  resetToDefaults: () => void;
}

// 默认设置
const defaultSettings: AppSettings = {
  autoHide: false,
  startupPosition: { x: 100, y: 100 },
  startupSize: { width: 1200, height: 800 },
  enableGlobalShortcuts: true,
  minimizeToTray: true,
  autoStart: false,
  theme: 'dark'
};

const defaultShortcuts: ShortcutConfig = {
  toggleVisibility: 'Ctrl+Shift+H',
  increaseOpacity: 'Ctrl+Shift+Up',
  decreaseOpacity: 'Ctrl+Shift+Down',
  toggleDisguise: 'Ctrl+Shift+D'
};

const defaultOpacityPresets = [0.3, 0.5, 0.7, 0.9, 1.0];

export const useAppStore = create<AppState>()(
  persist(
    (set) => ({
      // 初始状态
      currentMode: 'reading',
      opacity: 0.9,
      alwaysOnTop: false,
      isVisible: true,
      windowInfo: null,
      opacityPresets: defaultOpacityPresets,
      shortcuts: defaultShortcuts,
      settings: defaultSettings,
      wechatReadUrl: 'https://weread.qq.com/',
      isLoggedIn: false,
      disguiseSettings: {
        theme: 'dark',
        projectName: 'react-project',
        activeFile: 'App.tsx',
        terminalOutput: [
          '$ npm run dev',
          '> vite',
          '',
          '  VITE v5.0.0  ready in 234 ms',
          '',
          '  ➜  Local:   http://localhost:5173/',
          '  ➜  Network: use --host to expose',
          '  ➜  press h to show help'
        ]
      },
      
      // 设置方法
      setCurrentMode: (mode) => set({ currentMode: mode }),
      
      setOpacity: (opacity) => set({ opacity: Math.max(0.1, Math.min(1.0, opacity)) }),
      
      setAlwaysOnTop: (alwaysOnTop) => set({ alwaysOnTop }),
      
      setIsVisible: (isVisible) => set({ isVisible }),
      
      setWindowInfo: (windowInfo) => set({ windowInfo }),
      
      setOpacityPresets: (presets) => set({ opacityPresets: presets }),
      
      setShortcuts: (shortcuts) => set({ shortcuts }),
      
      setSettings: (settings) => set({ settings }),
      
      updateSetting: (key, value) => set((state) => ({
        settings: { ...state.settings, [key]: value }
      })),
      
      setWechatReadUrl: (url) => set({ wechatReadUrl: url }),
      
      setIsLoggedIn: (isLoggedIn) => set({ isLoggedIn }),
      
      setDisguiseSettings: (newSettings) => set((state) => ({
        disguiseSettings: { ...state.disguiseSettings, ...newSettings }
      })),
      
      // 操作方法
      toggleMode: () => set((state) => ({
        currentMode: state.currentMode === 'reading' ? 'disguise' : 'reading'
      })),
      
      toggleVisibility: () => set((state) => ({ isVisible: !state.isVisible })),
      
      increaseOpacity: () => set((state) => {
        const currentIndex = state.opacityPresets.findIndex(preset => preset >= state.opacity);
        const nextIndex = Math.min(currentIndex + 1, state.opacityPresets.length - 1);
        return { opacity: state.opacityPresets[nextIndex] || state.opacity };
      }),
      
      decreaseOpacity: () => set((state) => {
        const currentIndex = state.opacityPresets.findIndex(preset => preset >= state.opacity);
        const prevIndex = Math.max(currentIndex - 1, 0);
        return { opacity: state.opacityPresets[prevIndex] || state.opacity };
      }),
      
      resetToDefaults: () => set({
        opacity: 0.9,
        alwaysOnTop: false,
        opacityPresets: defaultOpacityPresets,
        shortcuts: defaultShortcuts,
        settings: defaultSettings,
        disguiseSettings: {
          theme: 'dark',
          projectName: 'react-project',
          activeFile: 'App.tsx',
          terminalOutput: [
            '$ npm run dev',
            '> vite',
            '',
            '  VITE v5.0.0  ready in 234 ms',
            '',
            '  ➜  Local:   http://localhost:5173/',
            '  ➜  Network: use --host to expose',
            '  ➜  press h to show help'
          ]
        }
      })
    }),
    {
      name: 'wechat-read-fish-storage', // 本地存储的key
      partialize: (state) => ({
        // 只持久化这些状态
        opacity: state.opacity,
        alwaysOnTop: state.alwaysOnTop,
        opacityPresets: state.opacityPresets,
        shortcuts: state.shortcuts,
        settings: state.settings,
        wechatReadUrl: state.wechatReadUrl,
        disguiseSettings: state.disguiseSettings
      })
    }
  )
);

// 导出一些有用的选择器
export const useOpacity = () => useAppStore((state) => state.opacity);
export const useCurrentMode = () => useAppStore((state) => state.currentMode);
export const useAlwaysOnTop = () => useAppStore((state) => state.alwaysOnTop);
export const useIsVisible = () => useAppStore((state) => state.isVisible);
export const useShortcuts = () => useAppStore((state) => state.shortcuts);
export const useSettings = () => useAppStore((state) => state.settings);
export const useDisguiseSettings = () => useAppStore((state) => state.disguiseSettings);

// 导出操作方法
export const useAppActions = () => useAppStore((state) => ({
  setCurrentMode: state.setCurrentMode,
  setOpacity: state.setOpacity,
  setAlwaysOnTop: state.setAlwaysOnTop,
  setIsVisible: state.setIsVisible,
  toggleMode: state.toggleMode,
  toggleVisibility: state.toggleVisibility,
  increaseOpacity: state.increaseOpacity,
  decreaseOpacity: state.decreaseOpacity,
  resetToDefaults: state.resetToDefaults
}));